<?php
/**
 * CreateTime: 2023/12/5 16:21
 * User:LinQ
 */

namespace App\Http\Service\User;

use App\Facade\UserFuncFacade;
use App\Func\System\OperateLogFunc;
use App\Http\Service\BasicInterfaceService;
use App\Models\CompanyDepartment\DepartmentModel;
use App\Models\CompanyDepartment\DepartmentUserModel;
use App\Models\Users\UsersModel;
use App\State\StatusState;

class ManageUserService implements BasicInterfaceService
{
    public function getList(array $prams)
    {
        $page_size = $prams['page_size'] ?? 10;
        $filters = $prams['filters'] ?? [];
        $desc = $prams['desc'] ?? [];
        $usersModel = new UsersModel();
        $this->listSelectDefaultFilters($usersModel);
        if($filters){
            $this->listSelectFilters($usersModel,$filters);
        }
        $res = $usersModel->cListHasCom($usersModel,$page_size,$desc,[
            '*',
            'com_id as com_str'
        ]);
        // 处理数据
        $res['data'] = $this->dispose($res['data']);
        s_c_return($res,trans('message.get_list_ok',[
            'name' => trans('key.user')
        ]));
    }

    public function getSelectHasPage($prams)
    {
        $page_size = $prams['page_size'] ?? 10;
        $filters = $prams['filters'] ?? [];
        $desc = $prams['desc'] ?? [];
        $usersModel = (new UsersModel());
        $this->listSelectDefaultFilters($usersModel);
        if($filters){
            $this->listSelectFilters($usersModel,$filters);
        }
        $res = $usersModel->cListHasCom($usersModel,$page_size,$desc,[
            'name as value'
        ]);
        // 处理数据
        $res['data'] = $this->dispose($res['data']);
        s_c_return($res,trans('message.get_list_ok',[
            'name' => trans('key.user')
        ]));
    }

    public function listSelectDefaultFilters($query){
        $query->pushFilter('status',1);
    }

    public function listSelectFilters($query, $filters)
    {
        $filters = trim_array($filters);
        if(map_has_value($filters,'name')){
            $query->pushFilter('name',$filters['name'],'like');
        }
        if(map_has_value($filters,'phone')){
            $query->pushFilter('phone',$filters['phone'],'like');
        }
        if(map_has_value($filters,'account')){
            $query->pushFilter('account',$filters['account'],'like');
        }
        if(map_has_value($filters,'email')){
            $query->pushFilter('email',$filters['email'],'like');
        }
    }

    public function getSelect()
    {
        $usersModel = new UsersModel();
        $res = $usersModel->scopeAddComIdWhere()->select([
            'user_id as key',
            'name as value'
        ])->where('status',1)->get();
        s_c_return($res,trans('message.get_list_ok',[
            'name' => trans('key.user')
        ]));
    }

    public function getInfo($id)
    {
        $usersModel = new UsersModel();
        $res = $usersModel->select([
            "*"
        ])->scopeAddComIdWhere()->where('user_id',$id)->first();

        s_c_return($res,trans('message.get_detail_ok',[
            'name' => trans('key.user')
        ]));
    }

    public function create($data)
    {
        $usersModel = new UsersModel();
        $userInfo =  UserFuncFacade::getLoginInfo();
        $puPvKey = rsa_pu_pv_key();
        // 这里需要判断当前部门是否存在于此公司下
        $departmentInfo = DepartmentModel::where('com_id',$data['com_id'])
            ->where('department_id',$data['department_id'])->first();
        if(!$departmentInfo){
            s_fail_return(null,trans('message.name1_not_has_name2',[
                'name1' => trans('key.company'),
                'name2' => trans('key.department')
            ]));
        }

        // 校验直属领导是否属于本公司
        if(map_has_value($data,'leader_id')){
            $userInfo = UsersModel::where('com_id',$data['com_id'])->where('user_id',$data['leader_id'])->first();
            if(!$userInfo){
                s_fail_return(null,trans('message.name1_not_has_name2',[
                    'name1' => trans('key.company'),
                    'name2' => trans('key.user')
                ]));
            }
        }

        // 设置默认数据
        $insertData = [
            'name' => $data['name'],
            'account' => $data['account'],
            'com_id' => $data['com_id'],
            'password' => UserFuncFacade::getHashPassByUser($data['password']),
            'email' => $userInfo['email'] ?? "",
            'phone' => $userInfo['phone'] ?? "",
            'leader_id' => $userInfo['leader_id'] ?? 0,
            'union_id' => (\Symfony\Component\Uid\UuidV4::v6()->toRfc4122()),
            'pu_key' => $puPvKey['pu_key'],
            'pv_key' => $puPvKey['pv_key'],
            'created_at' => date("Y-m-d h:i:s"),
            'updated_at' => date("Y-m-d h:i:s"),
            'status' => 1
        ];
        $user_id = $usersModel->insertGetId($insertData);
        // 绑定用户和部门的关联表
        (new DepartmentUserModel())->insertGetId([
            'user_id' =>  $user_id,
            'department_id' => $data['department_id'],
            'created_at' => date("Y-m-d h:i:s"),
            'updated_at' => date("Y-m-d h:i:s"),
        ]);

        // 添加操作记录
        OperateLogFunc::addOperate(
            'ManageUserService',$user_id,'create');

        s_c_return(['user_id'=>$user_id],trans('message.created_ok',[
            'name' => trans('key.user')
        ]));
    }

    public function fakeDelete($id)
    {
        $usersModel = new UsersModel();
        // 判断当前用户是否是其他客户的直属领导
        $subUser = $usersModel->select([
            "user_id",
        ])
        ->where('leader_id',$id)
        ->where('status',StatusState::OK_STATUS)
        ->get();
        if($subUser->toArray()){
            s_fail_return(null,trans('message.has_sub_user').trans('message.del_err',[
                'name' => trans('key.user')
            ]));
        }
        // 通过状态机修改状态
        $res = (new StatusState())->stateChange($id,
            StatusState::OK_STATUS,
            StatusState::DELETE_STATUS,
            $usersModel,
            'user_id'
        );
        if(!$res){
            s_fail_return(null,trans('message.fake_del_err',[
                'name' => trans('key.user')
            ]));
        }
        s_c_return(null,trans('message.fake_del_ok',[
            'name' => trans('key.user')
        ]));
    }

    public function delete($data)
    {

    }

    public function update($data)
    {
        $user_id = $data['user_id'] ?? 0;
        $usersModel = new UsersModel();
        // 获取当前用户的详情
        $userInfo = $usersModel
            ->select([
                'com_id',
            ])
            ->where('user_id',$user_id)
            ->where('status',StatusState::OK_STATUS)
            ->first();
        if(!$userInfo){
            s_c_return(null,trans('message.update_err',[
                'name' => trans('key.user')
            ]));
        }
        if(map_has_value($data,'password')){
            $data['password'] = UserFuncFacade::getHashPassByUser($data['password']);
        }

        if(map_has_value($data,'department_id')){
            // 这里需要判断当前部门是否存在于此公司下
            $departmentInfo = DepartmentModel::where('com_id',$userInfo['com_id'])
                ->where('department_id',$data['department_id'])->first();
            if(!$departmentInfo){
                s_fail_return(null,trans('message.name1_not_has_name2',[
                    'name1' => trans('key.company'),
                    'name2' => trans('key.department')
                ]));
            }
        }

        // 校验直属领导是否属于本公司
        if(map_has_value($data,'leader_id')){
            $userInfo = UsersModel::where('com_id',$userInfo['com_id'])
                ->where('user_id',$data['leader_id'])->first();
            if(!$userInfo){
                s_fail_return(null,trans('message.name1_not_has_name2',[
                    'name1' => trans('key.company'),
                    'name2' => trans('key.user')
                ]));
            }
        }

        try {
            $res = $usersModel->where('user_id',$user_id)->update($data);
            if($res){
                // 添加操作记录
                OperateLogFunc::addOperate(
                    'ManageUserService',$res,'update'
                );
                s_c_return(null,trans('message.update_ok',[
                    'name' => trans('key.user')
                ]));
            }
            s_c_return(null,trans('message.update_err',[
                'name' => trans('key.user')
            ]));
        }catch (\Exception $exception){
            s_c_return(null,trans('message.update_err',[
                'name' => trans('key.user')
            ]));
        }

    }

    public function dispose($data): mixed
    {
        return $data;
    }

    public function fakeDeleteByIds($ids)
    {

    }

    public function getCurrentUserInfo(){
        $currentInfo = UserFuncFacade::getLoginInfo();
        $userAuth = UserFuncFacade::getUserAuth($currentInfo['user_id'],[
            'auth.auth_code',
            'auth.auth_name',
            'auth.auth_id',
            'auth.auth_type',
            'auth_value'
        ]);
        $userInfo = UsersModel::find($currentInfo['user_id']);
        $userInfo['auth'] = $userAuth;
        s_c_return($userInfo,trans('message.get_detail_ok',[
            'name' => trans('key.user')
        ]));
    }
}
